package com.gitee.zycra.future.job.common.filter;

import com.gitee.zycra.future.job.common.bo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zycra
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResult<String> handleValidationException(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        String message = objectError.getDefaultMessage();
        log.warn("param check failed, message={}", message);
        return CommonResult.failed(message);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public CommonResult<String> handleException(Throwable t) {
        log.error("system error", t);
        return CommonResult.exception();
    }
}
